﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace SHW_UP.BP
{
    class InfoUtils
    {
        /// <summary>
        /// 
        /// </summary>
        public static Hashtable parTable = new Hashtable();
        public static Hashtable sendInfoTable = new Hashtable();
        /// <summary> 
        /// 字符串转16进制字节数组 
        /// </summary> 
        /// <param name="hexString"></param> 
        /// <returns></returns> 
        public static byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary> 
        /// 字节数组转16进制字符串 
        /// </summary> 
        /// <param name="bytes"></param> 
        /// <returns></returns> 
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        #region 校验和  
        /// <summary>  
        /// 计算按位异或校验和（返回校验和值）  
        /// </summary>  
        /// <param name="Cmd">命令数组</param>  
        /// <returns>校验和值</returns>  
        public static byte GetXOR(byte[] Cmd)  
        {  
            byte check = (byte)(Cmd[0] ^ Cmd[1]);  
            for (int i = 2; i < Cmd.Length; i++)  
            {  
                check = (byte)(check ^ Cmd[i]);  
            }  
            return check;  
        }  
  
        /// <summary>  
        /// 计算按位异或校验和（返回包含校验和的完整命令数组）  
        /// </summary>  
        /// <param name="Cmd">命令数组</param>  
        /// <returns>包含校验和的完整命令数组</returns>  
        public static byte[] GetXORFull(byte[] Cmd)  
        {  
            byte check = GetXOR(Cmd);  
            List<byte> newCmd = new List<byte>();  
            newCmd.AddRange(Cmd);  
            newCmd.Add(check);
            newCmd.AddRange(Encoding.UTF8.GetBytes("#"));
            return newCmd.ToArray();  
        }  
        #endregion 

    }
}
